import datetime
import os.path
import sys

from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager


class Driver:
    driver = ""

    def __init__(self):
        options = webdriver.ChromeOptions()
        self.driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()), options=options)
        self.driver.implicitly_wait(5)  # 增加隐式等待时间

    def getScreeShot(self):
        try:
            # 获取基础目录路径
            base_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
            images_dir = os.path.join(base_dir, "images")

            # 创建日期目录
            dirname = datetime.datetime.now().strftime("%Y-%m-%d")
            dirpath = os.path.join(images_dir, dirname)

            if not os.path.exists(dirpath):
                os.makedirs(dirpath)

            # 获取调用方法名
            frame = sys._getframe().f_back
            method_name = frame.f_code.co_name if frame else "unknown"

            # 生成文件名
            filename = f"{method_name}-{datetime.datetime.now().strftime('%H%M%S')}.png"
            full_path = os.path.join(dirpath, filename)

            # 保存截图
            self.driver.save_screenshot(full_path)
            print(f"截图已保存至: {full_path}")
        except Exception as e:
            print(f"截图失败: {str(e)}")


# 创建全局Driver实例
BlogDriver = Driver()